﻿#include "CQue.h"
#include <string.h>

static int cque_push(CQue* thes, void* v) {
	CList* l = &thes->list;
	if (thes->is_with_lock) {
		thes->lock.wait(&thes->lock);
	}

	l->insert(l, (void*)&v);

	if (thes->is_with_lock) {
		thes->lock.signal(&thes->lock);
	}
	return 0;
}

static void* cque_pop(CQue* thes) {
	void* ret = 0;
	CList* l = &thes->list;
	CListIterator it;
	construct_clist_iterator(&it);

	if (0 >= l->cnt) {
		return 0;
	}
	it.ptr = l->begin(l);
	ret = *IT_PTR(it, void*);
	l->erase(l, &it);
	return ret;
}

static int cque_release(CQue* thes) {
	thes->list.release(&thes->list);
	return 0;
}

void construct_queue(CQue* thes, int with_lock) {
	construct_clist(&thes->list, sizeof(void*));
	thes->is_with_lock = with_lock;
	if (with_lock) {
		construct_sem(&thes->lock, 1);
	} else {
		memset(&thes->lock, 0, sizeof(thes->lock));
	}

	thes->push = cque_push;
	thes->pop = cque_pop;
	thes->release = cque_release;
}
